<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  
    <input type="file" name="file" id="file">
    <img src="" id="img" alt="">
    <button id="btn">提交</button>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
  <script>
    var file = document.querySelector("#file");
    var img = document.querySelector('#img');
    var btn  = document.querySelector('#btn');
    // 声明formData容器存储文件
    var formData = new FormData();
    
    file.onchange = function(){
      // 往容器中插入文件
      formData.append('file', this.files[0]);
      var fd = new FileReader();
      fd.readAsDataURL(this.files[0]);
      fd.onload = function(){
        img.src = this.result;
      }
    }
    //  ajax上传文件
    $("#btn").click(function(){

      if(file.files[0]) {
        $.ajax({
          url: '/upload',
          type: 'post',
          data: formData,
          processData: false, //必须 缓存关了
          contentType: false, //必须 关闭 设置 数据格式（以 数据本身格式为准 xxxxx urlencoded）
          success: function(res){
            console.log(res);
          }
        })
      }else{
        alert('请选择文件上传')
      }
    })
  </script>
</body>
</html>